<?php

namespace app\forms\item;

use yii\db\Exception;
use app\models\Item;
use yii\web\HttpException;
use app\validators\PositiveInteger;

/**
 * 权限项 编辑
 */
class UpdateForm extends BaseForm
{
    public $id;

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['id', PositiveInteger::class],
            ['id', 'required'],
            ['id', 'exist', 'targetClass' => Item::class],

            ['route', 'checkUnique'],
        ]);
    }

    public function checkUnique($attribute, $params)
    {
        $exist = Item::find()->select(['id'])->where(['and', ['route' => $this->$attribute], ['!=', 'id', $this->id]])->one();
        if ($exist)
            $this->addError($attribute, '路由已被占用');
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = new self;
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $attr = $form->getAttributes();
            $attr['parent_id'] = $attr['parentId'];
            $attr['data_auth'] = $attr['dataAuth'];
            unset($attr['id']);

            $model = Item::findOne($form['id']);
            $model->setAttributes($attr);
            $model->save(false);
        } catch (Exception $e) {
            $form->serverError();
        }

        $form->updateOk();
    }
}